package com.taoyuan.common.utils.file;

import java.io.File;

import com.taoyuan.common.constant.NumberConstants;
import com.taoyuan.common.constant.StringConstants;
import org.apache.commons.lang3.StringUtils;

/**
 * 文件类型工具类
 *
 * @author taoyuan
 */
public class FileTypeUtils {
    /**
     * 获取文件类型
     * <p>
     * 例如: taoyuan.txt, 返回: txt
     *
     * @param file 文件名
     * @return 后缀（不含".")
     */
    public static String getFileType(File file) {
        if (null == file) {
            return StringUtils.EMPTY;
        }
        return getFileType(file.getName());
    }

    /**
     * 获取文件类型
     * <p>
     * 例如: taoyuan.txt, 返回: txt
     *
     * @param fileName 文件名
     * @return 后缀（不含".")
     */
    public static String getFileType(String fileName) {
        int separatorIndex = fileName.lastIndexOf(".");
        if (separatorIndex < 0) {
            return "";
        }
        return fileName.substring(separatorIndex + 1).toLowerCase();
    }

    /**
     * 获取文件类型
     *
     * @param photoByte 文件字节码
     * @return 后缀（不含".")
     */
    public static String getFileExtendName(byte[] photoByte) {
        String strFileExtendName = StringUtils.EMPTY;
        boolean isGif = (photoByte[0] == NumberConstants.NUM71) && (photoByte[1] == NumberConstants.NUM73) && (photoByte[NumberConstants.NUM2] == NumberConstants.NUM70) && (photoByte[NumberConstants.NUM3] == NumberConstants.NUM56) && ((photoByte[4] == NumberConstants.NUM55) || (photoByte[4] == NumberConstants.NUM57)) && (photoByte[5] == NumberConstants.NUM97);
        boolean isJpg = (photoByte[NumberConstants.NUM6] == NumberConstants.NUM74) && (photoByte[NumberConstants.NUM7] == NumberConstants.NUM70) && (photoByte[NumberConstants.NUM8] == NumberConstants.NUM73) && (photoByte[NumberConstants.NUM9] == NumberConstants.NUM70);
        boolean isBpm = (photoByte[0] == NumberConstants.NUM66) && (photoByte[1] == NumberConstants.NUM77);
        boolean isPng = (photoByte[1] == NumberConstants.NUM80) && (photoByte[NumberConstants.NUM2] == NumberConstants.NUM78) && (photoByte[NumberConstants.NUM3] == NumberConstants.NUM71);
        if (isGif) {
            strFileExtendName = "GIF";
        } else if (isJpg) {
            strFileExtendName = "JPG";
        } else if (isBpm) {
            strFileExtendName = "BMP";
        } else if (isPng) {
            strFileExtendName = "PNG";
        }
        return strFileExtendName;
    }
}
